import React, { useEffect, useRef, useState, useMemo, useContext } from 'react';
import { SchemaManage } from '@/components/SchemaComponent';
import { connect, history } from 'umi';
import { MyAssetListManageAPI } from '../common/type';
import { getTableColumns } from '../mconfig';
import { assetListManageServices } from '../services';
import { AssetListManageContext } from '../mconfig/useManageContext';
import { useDataSourceTable } from '../mconfig/useDataSourceTable';
import { getInvoiceCode, getKeyRouter, getPersonalInfo, getPosName, getUserDepID, getUserDepName, getUserName } from '@/utils';
import moment from 'moment';

const AssetListTableManageView: React.FC<MyAssetListManageAPI.IMaterialManageView> = ({ curRes }) => {
  /** 管理页services */
  const {
    getAssetListTableData,
    assetListData,
    loading,
    pagination,
    searchList,
    // manageTableParams,
    otherParams,
    loadMdicMapList,
  } = assetListManageServices(curRes);

  /** 管理页的ref */
  const MaterialManageViewRef: any = useRef();

  /** 保存表格展开行的key值 */
  const [tableExpantKeys, setTableExpantKeys] = useState<string[]>([]);

  /** 保存展示的表格数据 */
  const [dataSourceTable, setDataSourceTable] = useState<Record<string, any>[]>([]);

  /** 处理是否有子合同 */
  const { onExpandTable, childLoading } = useDataSourceTable(assetListData?.rows, dataSourceTable, setDataSourceTable, tableExpantKeys, setTableExpantKeys);

  /** 切换头部方法 */
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    getAssetListTableData({ ...params, ...searchValues });
  };

  /** 重置方法 */
  const onReset = (otherParams: MyAssetListManageAPI.IAssetTableRequestType) => {
    getAssetListTableData({ ...otherParams });
  };

  /** 搜索方法 */
  const onSearch = (otherParams: MyAssetListManageAPI.IAssetTableRequestType) => {
    getAssetListTableData({ ...otherParams });
  };

  /** 表格刷新数据 */
  const reloadTableData = () => {
    getAssetListTableData({});
  };

  /** 分页方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getAssetListTableData({ pageSize, current, ...params });
  };

  /** Table操作列的事件池 */
  const operateFnc: MyAssetListManageAPI.IMaterialTableActionType = {
    /** 资产退库按钮 */
    onReturn: (record: Record<string, any>) => {
      let obj = {
        createTime: moment(new Date()).format('YYYY-MM-DD'),
        applyCode: getInvoiceCode('LY'),
        applyTitle: `${getUserName()}_${getUserDepName()}_${moment(new Date()).format('YYYY年_MM月')}_退库`,
        assetList: [{ ...record, materialOrAssetId: record?.id }],
        createrName: getUserName(),
        createPhone: getPersonalInfo()?.phoneMobile || '',
        createDepartmentName: getUserDepName(),
        createPositionName: getPosName(),
        useDepartmentID: getUserDepID(),
      };
      history.push({
        pathname: `/assetApplyUes/add/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'add',
          tkObj: obj,
          returnPathName: history.location.pathname,
        },
      });
    },
  };

  /** Table的columns集合 */
  const columns: Record<string, any>[] = useMemo(() => {
    let val = getTableColumns(curRes, operateFnc);
    // console.log("===========================>>>>val",val)
    // debugger
    return val;
  }, [curRes]);

  useEffect(() => {
    if (history.location.pathname == '/myAssetController/manage') {
      reloadTableData();
    }
  }, [history.location.pathname]);

  return (
    <>
      <div
        id={'custom-preview-container'}
        style={{
          position: 'relative',
          overflow: 'hidden',
          height: '100%',
          width: '100%',
        }}
      >
        <SchemaManage
          ref={MaterialManageViewRef}
          searchProps={{
            switchList: [], //头部切换列表
            searchList,
            onSwitch,
            onReset,
            onSearch,
          }}
          actionList={[]} // 操作按钮
          tableProps={{
            columns: columns,
            dataSource: dataSourceTable ? dataSourceTable : [],
            rowKey: 'id',
            loading: loading || childLoading,
            pagination: pagination as any,
            onPageChange: onPageChange,
            expandable: {
              // expandIcon: manageTableExpandIcon,
              onExpand: onExpandTable,
              expandedRowKeys: tableExpantKeys,
            },
          }}
        />
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AssetListTableManageView);
